import { BadRequestException, PipeTransform } from "@nestjs/common";
interface ParseArrayOptions {
  spearator?: string;
  items: any;
}

export class ParseArrayPipe implements PipeTransform<string, any[]> {
  private options: ParseArrayOptions;
  constructor(options: ParseArrayOptions) {
    this.options = options;
  }
  transform(value: string): any[] {
    if (!value) return [];
    const { items, spearator } = this.options;
    return value.split(spearator).map((item) => {
      if (items === String) {
        return item;
      } else if (items === Number) {
        const val = Number(item);
        if (isNaN(val)) {
          throw new BadRequestException("Validation failed");
        }
        return val;
      } else if (items === Boolean) {
        if (value.toLowerCase() === "true") {
          return true;
        } else if (value.toLowerCase() === "false") {
          return false;
        } else {
          throw new BadRequestException(
            "Validation failed (boolean string is expected))"
          );
        }
      }
    });
  }
}
